package com.sas.web.dataProvider;

import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

import com.sas.domain.Article;
import com.sas.model.EntityModel;
import com.sas.repository.ArticleRepository;
import com.sas.web.panel.articles.ArticleFieldTreePanel;


@SuppressWarnings("serial")
public class SortableArticleDataProvider extends SortableDataProvider<Article> {
	private ArticleFieldTreePanel aftp;
	private ArticleRepository articleRepository;
	private List<Article> sortedArticles;

	public SortableArticleDataProvider(ArticleFieldTreePanel aftp,
			String property, ArticleRepository articleRepository) {
		this.articleRepository = articleRepository;
		this.aftp = aftp;
		setSort(property, true);
	}
	
	@Override
	public Iterator<Article> iterator(int first, int count) {
		SortParam sp = getSort();
//		List<Article> ret = (List<Article>) articleRepository.findByArticleField(aftp.getSelectedArticleField(), sp.getProperty(), sp.isAscending()).subList(first, first + count);
//		List<Article> ret = (List<Article>) articleRepository.findAllSortedBy(sp.getProperty(), sp.isAscending()).subList(first, first + count);
		
		return sortedArticles == null ? null : sortedArticles.iterator();
	}

	@Override
	public IModel<Article> model(final Article object) {
		
		return new EntityModel<Article>(Article.class, object);

	}

	
	@Override
	public int size() {
		
		IModel<List<Article>> imodelArticles =  new LoadableDetachableModel<List<Article>>() {

			@Override
			protected List<Article> load() {
				return (List<Article>) articleRepository.findByArticleField(aftp.getSelectedArticleField().getObject(), getSort().getProperty(), getSort().isAscending());
			}
		};
		
//		sortedArticles = (List<Article>) articleRepository.findByArticleField(aftp.getSelectedArticleField(), sp.getProperty(), sp.isAscending());
		sortedArticles = imodelArticles.getObject();
		return sortedArticles == null ? 0 : sortedArticles.size();
	}

}
